package com.wanxi.service.Impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wanxi.mapper.PermissionMapper;
import com.wanxi.mapper.UserMapper;
import com.wanxi.model.UserModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;


/**
 * @author Li
 * @Date 2023/7/10 17:44
 */
@Service
public class UserSecurityServiceImpl implements UserDetailsService {
@Autowired
private UserMapper userMapper;
@Autowired
private PermissionMapper permissionMapper;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
//       从数据库中查询用户信息
        LambdaQueryWrapper<UserModel> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserModel::getUsername,username);
                UserModel userModel = userMapper.selectOne(queryWrapper);
//                如果没有查询到用户抛出异常
        if (Objects.isNull(userModel)){
            throw new RuntimeException("用户名或密码错误！");
        }
//        List<String> authorityList = new ArrayList<>(Arrays.asList("pass"));
List<String> authorityList = permissionMapper.selectPermissionByUserId(userModel.getId());
//       UserDetails userDetails = UserModel.builder()
//               .authorities(AuthorityUtils.createAuthorityList("pass"))
//               .build();
        //TODO 查询对应的权限
        userModel.setPermissions(authorityList);
     return  userModel;

    }
}
